<template>
  <div class="query-display-container">
    <!-- 用户信息区域 -->
    <div class="query-user-info">
      <el-avatar
        :size="avatarSize"
        :src="userAvatar"
        class="user-avatar"
      >
        <el-icon v-if="!userAvatar"><User /></el-icon>
      </el-avatar>

      <div class="user-details">
        <div class="user-name">
          {{ userName }}
          <el-tooltip v-if="userId" :content="'用户ID: ' + userId" placement="top">
            <el-icon class="info-icon"><InfoFilled /></el-icon>
          </el-tooltip>
        </div>
        <div v-if="showTime" class="query-time">{{ formatQueryTime }}</div>
      </div>
    </div>

    <!-- 查询内容 -->
    <div class="query-content">
      <div class="content-header">
        <span class="label">查询内容:</span>
        <div class="actions">
          <el-tooltip content="复制查询内容" placement="top">
            <el-button
              type="primary"
              text
              circle
              @click="copyContent"
              size="small"
            >
              <el-icon><CopyDocument /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>

      <div
        class="content-text"
        :class="{ 'is-collapsed': isCollapsed && shouldCollapse, 'clickable': shouldCollapse }"
        @click="isCollapsed && shouldCollapse ? toggleCollapse() : null"
      >
        <pre>{{ content }}</pre>
        <div v-if="isCollapsed && shouldCollapse" class="collapse-overlay">
          <el-button type="primary" text @click.stop="toggleCollapse">
            <el-icon><ArrowDown /></el-icon> 展开
          </el-button>
        </div>
      </div>
    </div>

    <!-- 查询参数 -->
    <div v-if="hasParameters" class="query-parameters">
      <div class="params-header">
        <span class="label">查询参数:</span>
      </div>

      <el-descriptions :column="parametersColumn" border>
        <el-descriptions-item
          v-for="(value, key) in parameters"
          :key="key"
          :label="getParamLabel(key)"
        >
          <el-tag v-if="isTagParam(key)" :type="getTagType(value)">
            {{ formatParamValue(key, value) }}
          </el-tag>
          <template v-else>{{ formatParamValue(key, value) }}</template>
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  User,
  InfoFilled,
  CopyDocument,
  ArrowDown
} from '@element-plus/icons-vue'
import { formatTimestamp } from '@/utils/queryDataProcessor'

const props = defineProps({
  // 用户信息
  userId: {
    type: [String, Number],
    default: ''
  },
  userName: {
    type: String,
    default: '匿名用户'
  },
  userAvatar: {
    type: String,
    default: ''
  },

  // 查询内容
  content: {
    type: String,
    required: true
  },

  // 查询时间
  queryTime: {
    type: [String, Number, Date],
    default: null
  },

  // 查询参数
  parameters: {
    type: Object,
    default: () => ({})
  },

  // 界面配置
  showTime: {
    type: Boolean,
    default: true
  },
  avatarSize: {
    type: Number,
    default: 40
  },
  collapsible: {
    type: Boolean,
    default: true
  },
  maxHeight: {
    type: Number,
    default: 200
  },
  parametersColumn: {
    type: Number,
    default: 2
  }
})

// 状态
const isCollapsed = ref(true)
const contentHeight = ref(0)

// 计算属性
const hasParameters = computed(() => {
  return props.parameters && Object.keys(props.parameters).length > 0
})

const shouldCollapse = computed(() => {
  return props.collapsible && contentHeight.value > props.maxHeight
})

const formatQueryTime = computed(() => {
  if (!props.queryTime) return ''
  return formatTimestamp(props.queryTime)
})

// 方法
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

const copyContent = () => {
  try {
    navigator.clipboard.writeText(props.content)
    ElMessage.success('已复制到剪贴板')
  } catch (err) {
    console.error('复制失败', err)
    ElMessage.error('复制失败，请手动复制')
  }
}

const getParamLabel = (key) => {
  // 常见参数名映射
  const labelMap = {
    'temperature': '温度',
    'max_tokens': '最大生成Token',
    'top_p': 'Top P',
    'top_k': 'Top K',
    'presence_penalty': '存在惩罚',
    'frequency_penalty': '频率惩罚',
    'stream': '流式输出',
    'stop': '停止词',
    'model': '模型'
  }

  return labelMap[key] || key
}

const isTagParam = (key) => {
  // 使用标签展示的参数
  return ['model', 'stream'].includes(key)
}

const getTagType = (value) => {
  // 根据值设置标签类型
  if (value === true || value === 'true') return 'success'
  if (value === false || value === 'false') return 'info'

  // 模型类型标签
  if (typeof value === 'string' && value.includes('gpt')) return 'primary'
  if (typeof value === 'string' && value.includes('claude')) return 'warning'

  return ''
}

const formatParamValue = (key, value) => {
  // 格式化布尔值
  if (value === true) return '是'
  if (value === false) return '否'

  // 格式化数组
  if (Array.isArray(value)) {
    return value.join(', ')
  }

  // 格式化数字
  if (key === 'temperature' && typeof value === 'number') {
    return value.toFixed(2)
  }

  return value
}

// 生命周期钩子
onMounted(() => {
  // 计算内容高度，用于判断是否需要折叠
  const contentElement = document.querySelector('.content-text pre')
  if (contentElement) {
    contentHeight.value = contentElement.scrollHeight
  }
})
</script>

<style scoped>
.query-display-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  border-radius: 8px;
  background-color: var(--el-bg-color-page);
}

.query-user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  flex-shrink: 0;
  border: 2px solid var(--el-color-primary-light-7);
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-weight: bold;
  color: var(--el-text-color-primary);
  display: flex;
  align-items: center;
  gap: 6px;
}

.info-icon {
  color: var(--el-color-info);
  font-size: 14px;
  cursor: pointer;
}

.query-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.query-content {
  width: 100%;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.label {
  font-weight: bold;
  color: var(--el-text-color-regular);
}

.actions {
  display: flex;
  gap: 4px;
}

.content-text {
  position: relative;
  width: 100%;
  border-radius: 4px;
  background-color: var(--el-fill-color-light);
  padding: 12px;
  transition: all 0.3s;
}

.content-text.is-collapsed {
  max-height: v-bind('props.maxHeight + "px"');
  overflow: hidden;
}

.content-text.clickable {
  cursor: pointer;
}

.content-text pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
  font-family: 'Courier New', monospace;
  line-height: 1.5;
}

.collapse-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: linear-gradient(transparent, var(--el-fill-color-light) 70%);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  padding-bottom: 8px;
}

.query-parameters {
  width: 100%;
}

.params-header {
  margin-bottom: 8px;
}

:deep(.el-descriptions__cell) {
  padding: 8px 12px;
}

@media (max-width: 768px) {
  :deep(.el-descriptions__label) {
    width: 100px;
  }
}
</style>
